/**
 * Created by Apple on 2017/3/9.
 */

var crypto = require('crypto');
var uuid = require("node-uuid");
var https = require("https");
var http = require("http");
var Url = require("url");
var querystring = require("querystring");
var ttutil = {};


/**
 * sha1加密， 并大写输出
 * @param text
 * @returns {string}
 */
ttutil.sha1 = function (text) {
    var shasum = crypto.createHash('sha1');
    shasum.update(text);
    return shasum.digest('hex').toUpperCase();
};

ttutil.getByteLen = function (val) {
    var len = 0;
    for (var i = 0; i < val.length; i++) {
        if (val[i].match(/[^\x00-\xff]/ig) != null) //全角
            len += 2;
        else
            len += 1;
    }
    return len;
};


ttutil.testIdentity = function (code) {
    var city = [11, 12, 13, 14, 15, 21, 22, 23, 31, 32, 33, 34, 35, 36, 37, 41, 42, 43, 44, 45, 46, 50, 51, 52, 53, 54, 61, 62, 63, 64, 65, 71, 81, 82, 91];
    var pass = true;
    if (!code || code.length != 18 || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])([012]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
        pass = false;
    }
    else if (city.indexOf(Number(code.substr(0, 2))) == -1) {
        pass = false;
    }
    else {
        //18位身份证需要验证最后一位校验位
        code = code.split('');
        //∑(ai×Wi)(mod 11)
        //加权因子
        var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        //校验位
        var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
        var sum = 0;
        var ai = 0;
        var wi = 0;
        for (var i = 0; i < 17; i++) {
            ai = Number(code[i]);
            wi = factor[i];
            sum += ai * wi;
        }
        var last = parity[sum % 11];
        if (last != code[17]) {
            pass = false;
        }
    }
    return pass;
};
ttutil.testAccount = function (account) {
    return /^[0-9a-zA-Z_.@]{6,20}$/.test(account);
};

ttutil.testPassword = function (password) {
    return /^\S{6,20}$/.test(password) && ttutil.getByteLen(password) == password.length;
};

ttutil.testNickname = function (nickname) {
    if (!nickname) {
        return false;
    }
    return nickname.length > 0 && nickname.length <= 16 && !nickname.match(/\s/) && !nickname.match(/\"|\'|\;|\:|\,|\{|\}|\[|\]|\)|\(/gi);
};

ttutil.md5 = function (text) {
    return crypto.createHash('md5').update(text, "utf-8").digest('hex');
};
//生成rsa签名
ttutil.getRsaSign = function (privatePem, data) {


    var key = privatePem.toString();
    var sign = crypto.createSign('RSA-SHA1');
    sign.write(data, "utf-8");
    sign.end();
    return sign.sign(key, 'base64');
};
//验证rsa签名
ttutil.verifyRsaSign = function (publicPem, sign, data) {


    var pubkey = publicPem.toString();
    var verify = crypto.createVerify('RSA-SHA1');
    verify.update(data, "utf-8");


    return verify.verify(pubkey, sign, 'base64');
};

ttutil.getClientIP = function (req) {
    var ipAddress;
    var headers = req.headers;
    var forwardedIpsStr = headers['x-real-ip'] || headers['x-forwarded-for'];
    forwardedIpsStr ? ipAddress = forwardedIpsStr : ipAddress = null;
    if (!ipAddress) {
        ipAddress = req.connection.remoteAddress;
    }


    if (ipAddress.substr(0, 7) == "::ffff:") {
        return ipAddress.substr(7);
    }


    return ipAddress;
};


ttutil.getUUID = function () {
    return uuid.v4();
};

/**
 * 生成紧凑的时间格式， 如 2010-1-13 10:02:03 会变成 20100113100203
 * @param date
 * @returns {string}
 */
ttutil.toCompactLocaleString = function (date) {

    date = date || new Date();
    var dateString = "";
    var oldDateString = date.toLocaleString().replace(/-([1-9])-/, "-0$1-").replace(/-([1-9]) /, "-0$1 ");
    while (dateString != oldDateString) {
        dateString = oldDateString;
        oldDateString = oldDateString.replace("-", "");
        oldDateString = oldDateString.replace(" ", "");
        oldDateString = oldDateString.replace(":", "");
    }
    return dateString;
};

/**
 * 生成成一个合法的 orderID
 */
var lastTimeStamp = ttutil.toCompactLocaleString();
var times = 10000;
ttutil.generateOrderID = function () {


    var timeStamp = ttutil.toCompactLocaleString();

    if (timeStamp != lastTimeStamp) {
        lastTimeStamp = timeStamp;
        times = 10000;
    }
    times++;

    var orderID = "qymf_" + timeStamp + "_" + times;

    return orderID;
};


var keyArray = [5, 2323, 321845, 329857689, 32, 1230, 4, 10000, 32, 8, 7764, 12, 3232, 800, 103, 8274, 5778];
ttutil.simpleSign = function (data) {
    var s = 0;
    for (var i = 0; i < data.length; ++i) {
        s += data.charCodeAt(i) % keyArray[i % keyArray.length];
    }
    return s;
};

ttutil.calcSign = function (data, key) {
    var arr = this.paraFilterAndSort(data);

    var content = this.linkString(arr);

    var lastValue = content + "&key=" + key;

    var sign = "x" + ttutil.simpleSign(lastValue) + "x";


    return sign;
};

/**
 * 过渡参数, 除去数组中的空值和签名参数, 排序
 * @param args
 * @returns {Array}
 */
ttutil.paraFilterAndSort = function (args) {
    var r = [];
    for (var attr in args) {
        if (attr == "sign" || args[attr] == "" || args[attr] == null) {
            continue;
        }
        r.push({key: attr, value: args[attr]});
    }

    r.sort(function (a, b) {
        return a.key > b.key ? 1 : -1;
    });

    return r;
};

/**
 * 链接参数
 * @param arr
 */
ttutil.linkString = function (arr) {
    var content = "";
    for (var i = 0; i < arr.length; ++i) {
        content += arr[i].key + "=" + arr[i].value + "&";
    }
    return content.substring(0, content.length - 1);//
};

/**
 * 计算出密码
 * @param account
 * @param password
 */
ttutil.calcPassword = function (account, password) {
    return ttutil.md5(account + "qymf" + password);
};


ttutil.get = function (url, callback) {

    var ooo;
    if (url.startsWith("https")) {
        ooo = https;
    }
    else {
        ooo = http;
    }
    ooo.get(url, (res) => {
        var vData = "";
        res.on('data', (d) => {
            vData += d;
        });
        res.on('end', () => {
            callback && callback(vData, res);
        });

    }).on('error', (e) => {
        console.error(e);
    });
};

ttutil.post = function (url, postData, callback) {

    var urlObj = Url.parse(url);

    if (typeof postData == "object") {
        postData = JSON.stringify(postData);
    }

    var ooo;
    if (urlObj.protocol == "https:") {
        ooo = https;
    }
    else {
        ooo = http;
    }
    var options = {
        hostname: urlObj.hostname,
        port: urlObj.port || 443,
        path: urlObj.path,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': Buffer.byteLength(postData)
        }
    };

    var req = ooo.request(options, (res) => {

        var vData = "";
        res.on('data', (d) => {
            vData += d;
        });
        res.on("end", () => {
            callback && callback(vData, res);
        })
    });
    req.on('error', (e) => {
        console.error(e);
    });
    req.write(postData);
    req.end();
};

ttutil.trimMap = (map) => {
    //去掉前后空格
    for (var key in map) {
        if (typeof map[key] == 'string') {
            map[key] = map[key].trim();
        }
        else if (typeof map[key] == 'object') {
            this.trimMap(map[key]);
        }
    }
};


// var packageNameArray = [
//     "buildhouse",
//     "takecarebaby",
//     "catchfish",
//     "cube2048",
//     "abc",
//     "vehicle",
//     "shape",
//     "fruits",
//     "vegetables",
//     "bomber",
//     "popstar",
// ];
//
// for(var i = 0; i < packageNameArray.length; ++i){
//     ttutil.get("https://htqymf.qiyimofang.com/api/admin/get_app_info?packageName="+ packageNameArray[i], (vData, res) => {
//         console.log(vData);
//     });
// }


module.exports = ttutil;